﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;
namespace K.EnterpriseLibary
{
    /// <summary>
    /// 安全文件
    /// </summary>
    /// 
    public enum ReadOrWrite
    {
        Read,
        Write
    }
    public class SafeFileStream : System.IO.FileStream
    {
        string _RealFileName;
        ReadOrWrite _ReadOrWrite;

        // 讀的時候打開
        public SafeFileStream(string path, ReadOrWrite readOrWrite)
            : base(
                readOrWrite == ReadOrWrite.Read ? path : GetTempFileName(path)
                , readOrWrite == ReadOrWrite.Read ? FileMode.Open : FileMode.Create
                , readOrWrite == ReadOrWrite.Read ? FileAccess.Read : FileAccess.Write)
        {
            _RealFileName = path;
            _ReadOrWrite = readOrWrite;
        }

        public override void Close()
        {
            base.Close();
            if (_ReadOrWrite == ReadOrWrite.Write)
            {
                // 由於是臨時文件，所以先保存，然後複製到正式文件，刪除臨時文件
                System.IO.File.Copy(GetTempFileName(_RealFileName), _RealFileName, true);
                System.IO.File.Delete(GetTempFileName(_RealFileName));
            }
        }

        static string GetTempFileName(string fileName)
        {
            return fileName + ".temp~";
        }
    }
}
